import React, { useState, useEffect, useRef } from 'react';
import { useRequest, useModel } from 'umi';
import { Row, Col, Card, Tabs, Descriptions, Divider, message,notification,Space,Tooltip } from 'antd';
import { getMonitoringDevicInfo, getEChartsOption, getMonitoringPhase } from '@/services/deviceLive';
import { queryDeviceAlarm } from '@/services/deviceAlarm';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import moment from 'moment'
import { queryAlarmRules} from '@/services/alarmRules';
import UpdateForm from '@/pages/alarm/record/components/UpdateForm';
import alarmcode from '@/utils/alarmcode-enum';
import RunData from '@/pages/monitoring/runData';
import styles from './index.less';
const { TabPane } = Tabs;
import { updateDeviceAlarm } from '@/services/deviceAlarm';

/**
 * 更新节点
 * @param fields
 */
 const handleUpdate = async (fields: any) => {
  const hide = message.loading('正在保存');
  try {
    await updateDeviceAlarm(fields);
    hide();
    message.success('保存成功');
    return true;
  } catch (error) {
    hide();
    message.error('保存失败请重试！');
    return false;
  }
};

const details: React.FC = (props: any) => {
 const { params } = props.match;
//  const { query:params } = props?.location;
 


  const [deviceInfo, setDeviceInfo] = useState<API.DeviceItem>({});
  const [runningData, setRunningData] = useState({});
  const [alarmSourceEnumDict, setAlarmSourceEnumDict] = useState({});
  const [alarmCategoryEnumDict, setAlarmCategoryEnumDict] = useState({});
  const [alarmLevelEnumDict, setAlarmLevelEnumDict] = useState({});
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  const [formValues, setFormValues] = useState({});

  const actionRef = useRef<ActionType>();

  const { initialState,setInitialState } = useModel('@@initialState');
  const { mySocket,dicts } = initialState || {};
  if (mySocket) {
    mySocket.send(params.deviceId);
    mySocket.onmessage =async function (e) {
      console.log(`onmessage: ${e.data}`);
      //排除心跳数据
      if ("heartbeat" != e.data&&e.data.indexOf("RunningData")!=-1) {
        onMessage(e);
      }else if ("heartbeat" != e.data&&e.data.indexOf("AlarmData")!=-1) {
        const data = JSON.parse(e.data);
        console.log(data.AlarmData)
        await setInitialState((s) => ({ ...s, alarmNotices: data.AlarmData }));
      }
    };
  }

  const onMessage = (e:any) => {
    const message = JSON.parse(e.data);
    const runningData = {...message.RunningData, ...message.ReliabilityData}
    runningData.acquisitionTime = moment().format("YYYY-MM-DD HH:mm:ss");
    setRunningData(runningData);
  }



  useEffect(() => {
    const setSelectData = async () => {
      var details = await getMonitoringDevicInfo({id:params.deviceId});
      if (details.deviceInfo) {
        details.deviceInfo.protocol = JSON.parse(details.deviceInfo.protocolConfig) || [];
      }
      setRunningData(details.runningData);
      setDeviceInfo(details.deviceInfo);
      
    }
    setSelectData();
    if(dicts){
      setAlarmSourceEnumDict(dicts["5Enum"]);
      setAlarmCategoryEnumDict(dicts["6Enum"]);
      setAlarmLevelEnumDict(dicts["8Enum"])

    }
  }, []);


 
const ruleColumns: ProColumns[] = [
    {
      title: '规则id',
      dataIndex: 'id',
    },
    {
      title: '规则名称',
      dataIndex: 'alarmName',
    },
    // {
    //   title: '设备名称',
    //   dataIndex: 'deviceName',
    // },
    {
      title: '变量名称',
      dataIndex: 'browseName',
   
    },
    {
      title: '报警级别',
      dataIndex: 'alarmLevel',
      valueEnum: alarmLevelEnumDict,
     
    },
    {
      title: '报警类别',
      dataIndex: 'alarmType',
      valueEnum: alarmCategoryEnumDict,
    
    },
    {
      title: '最大值',
      dataIndex: 'maxValue',
    
    },
    {
      title: '最小值',
      dataIndex: 'minValue',
    
    },
    {
      title: '是否启用',
      dataIndex: 'useState',
   
      valueEnum: {
        0: { text: "未启用" },
        1: { text: "已启用" }
      }
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      valueType: 'dateTime',
   
    }

  ];

  const columns: ProColumns[] = [
    {
      title: '变量名称',
      dataIndex: 'browseName',
   
    },
    {
      title: '报警时间',
      dataIndex: 'alarmTime',

    },
    {
      title: '报警类别',
      dataIndex: 'alarmType',
       valueEnum: alarmCategoryEnumDict
    },
    {
      title: '报警级别',
      dataIndex: 'alarmLevel',
      valueEnum:  alarmLevelEnumDict,
    },
    {
      title: '报警数值',
      dataIndex: 'alarmValue',
    }, {
      title: '信息来源',
      dataIndex: 'defectSource',
      valueEnum: alarmSourceEnumDict,
    },
    {
      title: '处置建议',
      search: false,
      width: 150,
      dataIndex: 'handleOpinions',
      render: (text, record) => (
        <Space size="middle"  className={styles.textOverflow}>
          <Tooltip placement="topLeft" title={text} arrowPointAtCenter>
           {text}
          </Tooltip>
        </Space>
       ),
    },
    {
      title: '处置状态',
      dataIndex: 'state',
      valueEnum: {0:'未处置',1:'已处置'}
    },
    {
      title: '报警处置信息',
      dataIndex: 'alarmAnswer',

    },



    {
      title: '操作',
      dataIndex: 'state',
      valueType: 'option',
      render: (text, record, _, action) => (
        <>
       {record.state==0?
        <a onClick={async () => {
            handleUpdateModalVisible(true);
            setFormValues(record);
          }}
        >处置</a>:null} 
        </>
      )
    },
  ];


  

  return (
    <div className={styles.main}>
      <Descriptions column={4} title={"设备基本信息"}>
        <Descriptions.Item label="设备位号">{deviceInfo?.deviceNo}</Descriptions.Item>
        <Descriptions.Item label="设备名称">{deviceInfo?.deviceName}</Descriptions.Item>
        <Descriptions.Item label="设备类型">{deviceInfo?.deviceTypeName}</Descriptions.Item>
        <Descriptions.Item label="驱动名称">{deviceInfo?.driverName}</Descriptions.Item>
        <Descriptions.Item label="驱动类型">{deviceInfo?.driverType == 0 ? "网口" : "串口"}</Descriptions.Item>
        <Descriptions.Item label="所在区域">{deviceInfo?.areaName}</Descriptions.Item>
        <Descriptions.Item label="所在位置">{deviceInfo?.devicePosition}</Descriptions.Item>
      </Descriptions>
      <Divider className={styles.divider} />
      <RunData type={deviceInfo?.deviceTypeId||2} runningData={runningData}></RunData>
      <Divider className={styles.divider} />
      <Row gutter={24} style={{ margin:0,marginBottom:'7px'}}>
      <Col xl={12} lg={12} md={12} sm={24} xs={24} className={styles.huanbiitem}>
        <ProTable
          headerTitle="报警规则"
          className={styles.alarmTable}
          // actionRef={actionRef}
          rowKey="id"
          search={false}
          request={(tableParams) => queryAlarmRules({ ...tableParams, ...params })}
          columns={ruleColumns}
          options={false}
          pagination={{
            defaultCurrent: 1,
            defaultPageSize: 10,
          }}
        /> 
      </Col>
      <Col xl={12} lg={12} md={12} sm={24} xs={24} className={styles.huanbiitem}>
        <ProTable
          headerTitle="报警"
          className={styles.alarmTable}
          actionRef={actionRef}
          rowKey="id"
          search={false}
          request={(tableParams) => queryDeviceAlarm({ ...tableParams, ...params })}
          columns={columns}
          options={false}
          pagination={{
            defaultCurrent: 1,
            defaultPageSize: 10,
          }}
        />
      </Col>
      </Row>
      {formValues && Object.keys(formValues).length ? (
        <UpdateForm
          onSubmit={async (value) => {
            const success = await handleUpdate(value);
            if (success) {
              handleUpdateModalVisible(false);
              setFormValues({});
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          onCancel={() => {
            handleUpdateModalVisible(false);
            setFormValues({});
          }}
          updateModalVisible={updateModalVisible}
          values={formValues}
      
        />
      ) : null}
    </div>
  );
};

export default details;